<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\CheckMemberLogin;
use App\Http\Controllers\Common\ajaxReturnJsonContent;
use DB;

class LoginController extends Controller
{
	/**
	 * [显示登录页面]
	 * @return [type] [description]
	 */
    public function login()
    {
    	return View('home.login');
    }

    /**
     * [处理登录]
     * @return [type] [description]
     */
    public function doLogin(CheckMemberLogin $request)
    {
    	//判断用户是否存在
    	$data = $this->isExistsUser($request->Member);
    	if (!$data) {
    		return redirect('Login')->with(['warning' => '用户不存在']);
    	}
        //判读用户的状态
        if ($data->status != 1) {
            return redirect('Login')->with(['warning' => '用户已被禁用，请反馈客服']);
        }
    	//判断密码是否正确
    	$bool = password_verify($request->password, $data->password);
    	if (!$bool) {
       		return redirect('Login')->with(['warning' => '密码错误']);
    	}

        //将用户信息存入session
    	$request->session()->put('Member', $data);

        //存入登录时间
        DB::table('shop_Member')->where(['email' => $data->email, 'phone' => $data->phone])
                                ->update(['accesstime' => date('y-m-d h:i:s',time())]);

    	return redirect('/');

    }

    /**
     * [ajax请求验证是否存在一个用户]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function ajaxRequestCheckIsExistsMember(Request $request)
    {
        if (!$request->ajax()) {
            return redirect('Login');
        }

        $res = $this->isExistsUser($request->Member);

        //处理成一个要被返回的数据
        $arr = ajaxReturnJsonContent::returnVal($res, '可用', '此用户不存在');

        if ($arr['code'] == 1) {
            $arr['status'] = $arr["data"]->status;
            //删除查询出来的用户的数据
            unset($arr["data"]);
        }
        return json_encode($arr);
    }
    /**
     * [验证用户是否存在]
     * @param  [string]  $user [要验证的用户]
     * @return obj       [查询出的数据，否则返回null]
     */
    protected function isExistsUser($user)
    {
    	return DB::table('shop_Member')->where('email', $user)
                                       ->orWhere('phone', $user)
                                       ->leftJoin('shop_MemberInfo', 'shop_Member.id', '=', 'shop_MemberInfo.Mid')
                                       ->first();
    }
    /**
     * [ajax判断验证码是否一致]
     * @param  [string] $captcha [要验证的验证码]
     * @return [type]          [description]
     */
    public function judgeCaptcha(Request $request) 
    {
        // 验证是否是ajax请求
        if (!$request->ajax()) {
            return redirect('Login');
        }
       return json_encode(ajaxReturnJsonContent::returnVal(session('Captch') == $request->captcha, '一致', '不一致'));
    }
}
